package cn.dada.dadarecipes.backend.merchant.service.impl;

import cn.dada.dadarecipes.backend.merchant.mapper.MerchantMapper;
import cn.dada.dadarecipes.backend.merchant.pojo.vo.MerchantInfoVo;
import cn.dada.dadarecipes.backend.merchant.pojo.vo.MerchantShopVO;
import cn.dada.dadarecipes.backend.merchant.service.MerchantService;
import cn.dada.dadarecipes.base.exception.ServiceException;
import cn.dada.dadarecipes.base.response.StatusCode;
import cn.dada.dadarecipes.base.util.HandleString;
//import cn.dada.dadarecipes.base.util.LoginValidation;
import cn.dada.dadarecipes.mall.product.mapper.ProductMapper;
import cn.dada.dadarecipes.mall.product.pojo.dto.ProductAddParam;
import cn.dada.dadarecipes.mall.product.pojo.dto.ProductEditParam;
import cn.dada.dadarecipes.mall.product.pojo.dto.ProductSelectParam;
import cn.dada.dadarecipes.mall.product.pojo.entity.Product;
import cn.dada.dadarecipes.mall.product.pojo.vo.ProductMerchantVO;
import cn.dada.dadarecipes.mall.shop.mapper.ShopMapper;
import cn.dada.dadarecipes.mall.shop.pojo.dto.ShopAddParam;
import cn.dada.dadarecipes.mall.shop.pojo.dto.ShopEditParam;
import cn.dada.dadarecipes.mall.shop.pojo.dto.ShopSelectParam;
import cn.dada.dadarecipes.mall.shop.pojo.entity.Shop;
import cn.dada.dadarecipes.user.order.mapper.OrderMapper;
import cn.dada.dadarecipes.user.order.pojo.dto.MerchantOrderUpdateParam;
import cn.dada.dadarecipes.user.order.pojo.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Slf4j
@Service
public class MerchantServiceImpl implements MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;


    /**
     * 业务层-商家登录
     * @param username
     * @param password
     * @param session
     * @return
     */
    @Override
    public MerchantInfoVo merchantLogin(String username, String password, HttpSession session) {
        log.debug("业务层-商家登录:username={},password={}", username, password);

        /* 判断当前商家是否已经登录 */
//        LoginValidation.MerchantAlreadyLogged(session);

        /* 从数据库中查询商家信息 */
        MerchantInfoVo merchant = Optional
                .ofNullable(merchantMapper.selectMerchant(username, password))
                .orElseThrow(()->new ServiceException(StatusCode.USERNAME_OR_PASSWORD_ERROR)); // 用户名或密码错误

        /* 登录成功，将商家id写入session */
        session.setAttribute("businessId", merchant.getId());
        return merchant;
    }

    /**
     * 业务层-商家退出登录
     * @param businessId
     * @param session
     */
    @Override
    public void merchantLogout(Long businessId, HttpSession session) {
        log.debug("业务层-商家退出登录:merchantId={}", businessId);
        session.removeAttribute("businessId");// 移除session
    }

    /**
     * 业务层-添加店铺
     * @param shopAddParam
     * @param session
     */
    @Override
    public void addShop(ShopAddParam shopAddParam, HttpSession session) {
        log.debug("业务层-添加店铺:shopAddParam={}", shopAddParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(shopAddParam.getBusinessId(), session);

        /* 判断店铺名称是否重复 */
        judgeShopNameIsRepeat(shopAddParam.getShopName());

        /* 添加店铺 */
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopAddParam, shop);
        shop.setStatus("1");//TODO 之后协调写个枚举类去存储状态 0-禁用 1-启用
        shop.setCreateTime(new Date());
        if (!shopMapper.addMerchantShop(shop)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 业务层-查询店铺
     * @param shopSelectParam
     * @param session
     * @return
     */
    @Override
    public List<MerchantShopVO> selectShop(ShopSelectParam shopSelectParam, HttpSession session) {
        log.debug("业务层-查询店铺:shopSelectParam={}", shopSelectParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(shopSelectParam.getBusinessId(), session);

        shopSelectParam.setShopName(HandleString.removeBlankStrings(shopSelectParam.getShopName()));// 去除空白字符串
        return shopMapper.selectMerchantShop(shopSelectParam);
    }

    /**
     * 业务层-编辑店铺
     * @param shopEditParam
     * @param session
     */
    @Override
    public void editShop(ShopEditParam shopEditParam, HttpSession session) {
        log.debug("业务层-编辑店铺:shopEditParam={}", shopEditParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(shopEditParam.getBusinessId(), session);

        /* 判断店铺名称是否重复 */
        judgeShopNameIsRepeat(shopEditParam.getShopName());

        /* 编辑店铺 */
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopEditParam, shop);
        shop.setShopName(HandleString.removeBlankStrings(shopEditParam.getShopName()));// 去除空白字符串
        shop.setUpdateTime(new Date());
        if (!shopMapper.updateMerchantShop(shop)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 业务层-删除店铺
     * @param id
     * @param businessId
     * @param session
     */
    @Override
    public void dropShop(Long id, Long businessId, HttpSession session) {
        log.debug("业务层-删除店铺:id={},businessId={}", id, businessId);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(businessId, session);

        /* 删除店铺 */
        if (!shopMapper.deleteMerchantShop(id,businessId)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
        /* 删除当前店铺下的所有商品 */
        productMapper.dropProduct(null, id, businessId);
    }

    /**
     * 业务层-添加商铺商品
     * @param productAddParam
     * @param session
     */
    @Override
    public void addProduct(ProductAddParam productAddParam, HttpSession session) {
        log.debug("业务层-添加商铺商品:productAddParam={}", productAddParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(productAddParam.getBusinessId(), session);

        /* 添加商品 */
        Product product = new Product();
        BeanUtils.copyProperties(productAddParam, product);
        product.setCreateTime(new Date());
        if (!productMapper.addMerchantProduct(product)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 业务层-查询商铺商品
     * @param productSelectParam
     * @param session
     * @return
     */
    @Override
    public List<ProductMerchantVO> selectProduct(ProductSelectParam productSelectParam, HttpSession session) {
        log.debug("业务层-查询商铺商品:productSelectParam={}", productSelectParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(productSelectParam.getBusinessId(), session);

        return productMapper.selectMerchantProduct(productSelectParam);
    }

    /**
     * 业务层-编辑商铺商品
     * @param productEditParam
     * @param session
     */
    @Override
    public void editProduct(ProductEditParam productEditParam, HttpSession session) {
        log.debug("业务层-编辑商铺商品:productEditParam={}", productEditParam);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(productEditParam.getBusinessId(), session);

        /* 编辑商品 */
        Product product = new Product();
        BeanUtils.copyProperties(productEditParam, product);
        product.setUpdateTime(new Date());
        if (!productMapper.updateMerchantProduct(product)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 业务层-删除商铺商品
     * @param id
     * @param businessId
     * @param session
     */
    @Override
    public void dropProduct(Long id, Long businessId, HttpSession session) {
        log.debug("业务层-删除商铺商品:id={},businessId={}", id, businessId);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(businessId, session);

        /* 删除商品 */
        if (!productMapper.dropProduct(id, null, businessId)) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    @Override
    public List<OrderVO> selectOrder(Long businessId, Long shopId, HttpSession session) {
        log.debug("查询商铺商品订单业务:businessId={},shopId={}", businessId, shopId);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(businessId, session);

        /* 查询当前商家商铺商品订单 */
        if (shopId == null) {// 查询当前商家所有商铺商品订单
            ShopSelectParam shopSelectParam = new ShopSelectParam();
            shopSelectParam.setBusinessId(businessId);
            List<MerchantShopVO> list = shopMapper.selectMerchantShop(shopSelectParam);

            List<Long> ids = list.stream()
                    .map(MerchantShopVO::getId)
                    .collect(Collectors.toList());

            return orderMapper.selectOrdersByIdsAndShopId(ids, null);
        }
        // 查询当前商家当前商铺所有商品订单
        return orderMapper.selectOrdersByIdsAndShopId(null, shopId);
    }

    @Override
    public void updateOrder(MerchantOrderUpdateParam param, HttpSession session) {
        log.debug("更新商铺商品订单业务:param={}", param);
        /* 判断当前商家是否登录 */
//        LoginValidation.isMerchantMyselfLogin(param.getBusinessId(), session);

        //TODO 更新订单
    }


    /**
     * 判断店铺名称是否重复
     * @param shopName
     */
    private void judgeShopNameIsRepeat(String shopName) {
        if (!shopMapper.selectMerchantShopByShopName(HandleString.removeBlankStrings(shopName)).isEmpty()) {
            throw new ServiceException(StatusCode.SHOP_NAME_REPEAT);
        }
    }
}
